import { useOpenState } from '@/hooks/modal';
import type { IPlank } from '@/types';
import { useSetState, useSize } from 'ahooks';
import { Button, Modal, Space, Upload, message } from 'antd';
import type { RcFile } from 'antd/es/upload/interface';
import { isEmpty, toArray } from 'lodash-es';
import { useRef } from 'react';

const fileTypes = ['application/json'];
const accept = fileTypes.join();

function validFileType(file: File) {
  return fileTypes.includes(file.type);
}

interface IPlankUploadProps {
  title: string;
  onUpload: (planks: IPlank[]) => void;
}

function PlankUpload(props: IPlankUploadProps) {
  const { title, onUpload } = props;
  function beforeUpload(file: RcFile) {
    if (!validFileType(file)) {
      message.error('file type error!');
    }
    file.text().then((json) => {
      const data = JSON.parse(json);
      onUpload(data.bomPlanks);
    });
    return false;
  }

  const childrenRef = useRef<HTMLElement>(null);
  const childrenSize = useSize(childrenRef);

  return (
    <div style={{ maxWidth: childrenSize?.width }}>
      <Upload
        maxCount={1}
        accept={accept}
        beforeUpload={beforeUpload}
        showUploadList={{ showRemoveIcon: false }}
      >
        <Button ref={childrenRef} type="primary">
          {title}
        </Button>
      </Upload>
    </div>
  );
}

export interface IUploadData {
  oldPlanks: IPlank[];
  newPlanks: IPlank[];
}

export interface IPlanksUploadProps {
  onConfirm(data: IUploadData): void;
}

export function PlanksUpload(props: IPlanksUploadProps) {
  const [state, setState] = useSetState<IUploadData>({
    oldPlanks: [],
    newPlanks: [],
  });
  const { open, show, hide } = useOpenState();
  function onOk() {
    props.onConfirm(state);
    hide();
  }
  const disabled = toArray(state).some(isEmpty);

  return (
    <>
      <Button type="primary" onClick={show}>
        上传数据
      </Button>
      <Modal
        open={open}
        onOk={onOk}
        onCancel={hide}
        okButtonProps={{ disabled }}
      >
        <Space align="start">
          <PlankUpload
            title="上传基准数据"
            onUpload={(planks) => {
              setState({ oldPlanks: planks });
            }}
          />
          <PlankUpload
            title="上传对比数据"
            onUpload={(planks) => {
              setState({ newPlanks: planks });
            }}
          />
        </Space>
      </Modal>
    </>
  );
}
